package main;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidDataSourceFactory;
import org.apache.commons.fileupload.FileItem;

import javax.swing.filechooser.FileSystemView;
import java.io.*;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;
import java.util.Random;

/**
 * 作者: ALIM-MASTIK
 * 创建实现: 2023/7/14 21:03
 * 项目名称：chat
 * 软件: IntelliJ IDEA
 */


public class JdbcUtils {
    public static File desktopDir = FileSystemView.getFileSystemView() .getHomeDirectory();

    public  static  String desktopPath = desktopDir.getAbsolutePath();

    private static DruidDataSource dataSource;

    static {
        try {
            Properties properties = new Properties();
            // 读取jdbc.properties属性配置文件
            InputStream inputStream = JdbcUtils.class.getClassLoader().getResourceAsStream("jdbc.properties");
            System.out.println(inputStream);
            // 从流中加载数据
            properties.load(inputStream);
            // 创建数据库连接池
            dataSource = (DruidDataSource) DruidDataSourceFactory.createDataSource(properties);

        } catch (Exception e) {
            System.out.println("as");
        }
    }

    /**
     * 获取数据库连接池中的连接
     *
     * @return 如果返回null，说明获取连接失败；有值就是获取连接成功
     */
    public static Connection getConnection() {
        Connection conn = null;
        try {
            conn = dataSource.getConnection();
        } catch (Exception e) {
            System.out.println("出问题了");
        }
        return conn;
    }
    /**
     * 关闭连接，放回数据库连接池
     *
     * @param conn 需要关闭的数据库连接对象
     */
    public static void close(Connection conn) {
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    public static void readImageToDB(String path,int UserID) {
        Connection connection=null;
        try {
            connection = getConnection();

            FileInputStream fileInputStream = new FileInputStream(path);
            String sql = "UPDATE  user_avatar SET   Avatar  = ? WHERE  UserID = ?";
            PreparedStatement preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setBinaryStream(1, fileInputStream, fileInputStream.available());
            preparedStatement.setInt(2,UserID);
            System.out.println(preparedStatement);
            try {
                int result = preparedStatement.executeUpdate();
                if (result > 0) {
                    System.out.println("更新成功");
                } else {
                    System.out.println("更新失败");
                }
            } catch (SQLException e) {
                System.out.println("");
            }

        } catch (SQLException | IOException e) {
            System.out.println(123321);
        }
    }
    public static void saveUserAvatarToDesktopTemp(Connection connection, int userId) {
        // 获取桌面路径

        // 创建temp文件夹路径
        String tempFolderPath = desktopPath + "/temp";
        // 检查并创建temp文件夹（如果不存在）
        File tempFolder = new File(tempFolderPath);
        if (!tempFolder.exists()) {
            tempFolder.mkdir();
        }
        // 准备查询语句
        String sql = "SELECT Avatar FROM user_avatar WHERE UserID = ?";
        try (PreparedStatement statement = connection.prepareStatement(sql)) {
            statement.setInt(1, userId);

            // 执行查询
            ResultSet resultSet = statement.executeQuery();
            if (resultSet.next()) {
                // 获取头像的二进制数据
                InputStream avatarStream = resultSet.getBinaryStream("Avatar");

                // 构建保存到文件的路径
                String avatarFilePath = "D:\\桌面\\Java\\chat\\web\\Temp\\"+userId + ".jpg";

                // 将头像保存到文件中
                try (OutputStream outputStream = new FileOutputStream("D:\\桌面\\Java\\chat\\web\\Temp\\"+userId + ".jpg")) {
                    byte[] buffer = new byte[1024];
                    int bytesRead;
                    while ((bytesRead = avatarStream.read(buffer)) != -1) {
                        outputStream.write(buffer, 0, bytesRead);
                    }
                    System.out.println("头像保存成功，路径：" + avatarFilePath);
                } catch (IOException e) {
                    System.err.println("保存头像时出现错误：" + e.getMessage());
                }
            } else {
                System.out.println("未找到指定用户的头像");
            }
        } catch (SQLException e) {
            System.err.println("查询数据库时出现错误：" + e.getMessage());
        }
    }
    public static void insertImageToDB(Connection connection, FileItem fileItem) throws SQLException, IOException {
        String sql = "UPDATE user_avatar SET Avatar=? WHERE UserID=?";
        try (PreparedStatement pstmt = connection.prepareStatement(sql)) {
            Random random = new Random();
            pstmt.setInt(2, 16);
//            pstmt.setString(2, "user_name"); // 假设要插入的用户名为user_name
            pstmt.setBlob(1, fileItem.getInputStream()); // 将图片数据插入到BLOB字段中
            System.out.println(pstmt);
//            pstmt.setBinaryStream(3,fileItem.getInputStream(), fileItem.getInputStream().available());
            // preparedStatement.setBinaryStream(1, fileInputStream, fileInputStream.available());
            pstmt.executeUpdate();
        }
    }
    public static boolean deleteFile(String filePath) {
        File file = new File(filePath);

        // 检查文件是否存在
        if (!file.exists()) {
            System.out.println("文件不存在：" + filePath);
            return false;
        }

        // 尝试删除文件
        if (file.delete()) {
            System.out.println("文件已成功删除：" + filePath);
            return true;
        } else {
            System.out.println("文件删除失败：" + filePath);
            return false;
        }
    }
    public static void main(String[] args) {
        System.out.println(getConnection());
        saveUserAvatarToDesktopTemp(getConnection(),1);
        System.out.println(deleteFile(desktopPath + "/temp/"+"1.jpg"));
    }
}